﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStruct
{
    /// <summary>
    /// 线性表-一维数组
    /// </summary>
    internal class Array
    {
        private int[] _array;//声明数组 用于存放数据
        int _length;//线性表的实际长度

        /// <summary>
        /// 初始化 这里我们给线性表初始化4个元素
        /// </summary>
        public void InitArray()
        {
            _array = new int[4];
            _array[0] = 15;
            _array[1] = 14;
            _array[2] = 9;
            _array[3] = 478;
            _length = 4;
        }

        /// <summary>
        /// 查询数组中是否存在某个值 如果存在返回该值在数组中的索引下标  如果不存在返回-1
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public int Get(int data)
        {
            for (int i = 0; i < _length; i++)
            {
                if (_array[i] == data)
                {
                    return i;
                }
            }
            return -1;
        }

        /// <summary>
        /// 在数组的指定位置插入一个值
        /// </summary>
        /// <param name="index"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool Insert(int index, int data)
        {
            if (_array.Length == _length)
            {
                int[] newArray = new int[_length * 2];
                for (int i = 0; i < _length; i++)
                {
                    newArray[i] = _array[i];
                }
                _array = newArray;
            }
            for (int i = _length - 1; i >= index; i--)
            {
                _array[i + 1] = _array[i];
            }
            _array[index] = data;
            _length++;
            return true;
        }

        /// <summary>
        /// 删除指定索引处的一个值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool Delete(int index)
        {
            for (int i = index; i < _length - 1; i++)
            {
                _array[i] = _array[i + 1];
            }
            _array[_length - 1] = 0;
            _length--;
            return true;
        }

        /// <summary>
        /// 修改数组指定位置的值
        /// </summary>
        /// <param name="index"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool Update(int index, int data)
        {
            if (index < 0 || index >= _length)
            {
                return false;
            }
            _array[index] = data;
            return true;
        }

        public void Print()
        {
            Console.Write($"总共{_length}个元素:");
            for (int i = 0; i < _length; i++)
            {
                Console.Write(_array[i] + " ");
            }
            Console.WriteLine();
        }
    }
}
